package com.springdemo.basic.global.service;


import com.springdemo.basic.global.dao.BaseDao;
import com.springdemo.basic.global.page.BasePage;
import com.springdemo.tools.ClassReflectUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

public abstract class BaseService<T>{
	
	public abstract BaseDao<T> getDao();

	@Transactional(rollbackFor=Exception.class)
	public int add(T t)  throws Exception{
		//设置主键.字符类型采用UUID,数字类型采用自增
		ClassReflectUtil.setIdKeyValue(t,"id",UUID.randomUUID().toString().replace("-",""));
		return getDao().add(t);
	}
	/**
	 * 考试系统add方法
	 * @param t  访问对象
	 * @param id 表主键ID
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public int addForExam(T t,String id)  throws Exception{
		//设置主键.字符类型采用UUID,数字类型采用自增
		ClassReflectUtil.setIdKeyValue(t,id,UUID.randomUUID().toString().replace("-",""));
		return getDao().add(t);
	}
	@Transactional(rollbackFor=Exception.class)
	public int update(T t)  throws Exception{
		return getDao().update(t);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public int updateBySelective(T t){
		return getDao().updateBySelective(t);
	}
	@Transactional(rollbackFor=Exception.class)
	public int delete(Object... ids) throws Exception{
		int count = 0;
		if(ids == null || ids.length < 1){
			return 0;
		}
		for(Object id : ids ){
			count += getDao().delete(id);
		}
		return count;
	}
	
	public int queryByCount(BasePage page)throws Exception{
		return getDao().queryByCount(page);
	}
	
	public List<T> queryByList(BasePage page) throws Exception{
		Integer rowCount = queryByCount(page);
		page.getPager().setRowCount(rowCount);
		return getDao().queryByList(page);
	}

	public T queryById(Object id) throws Exception{
		return getDao().queryById(id);
	}
}
